"""
ECS核心系统实现
"""
from typing import List, Dict, Type
import pygame
import random
from .entity import System, Entity
from .components import *

class RenderSystem(System):
    """渲染系统"""
    def __init__(self, screen: pygame.Surface):
        self.screen = screen
        self.layers: Dict[int, List[Entity]] = {}
        # 加载背景图片
        try:
            self.background = pygame.image.load("assets/S.png").convert()
        except:
            self.background = None
    
    def update(self, entities: List[Entity], delta_time: float):
        # 绘制背景
        if self.background:
            bg_width, bg_height = self.background.get_size()
            tiles_x = (self.screen.get_width() // bg_width) + 1
            tiles_y = (self.screen.get_height() // bg_height) + 1
            for i in range(tiles_x):
                for j in range(tiles_y):
                    self.screen.blit(self.background, (i * bg_width, j * bg_height))
        
        # 按层级分组实体
        self.layers.clear()
        for entity in entities:
            if not entity.has_component(Renderable) or not entity.has_component(Transform):
                continue
            
            renderable = entity.get_component(Renderable)
            if not renderable.visible:
                continue
                
            layer = renderable.layer
            if layer not in self.layers:
                self.layers[layer] = []
            self.layers[layer].append(entity)
        
        # 按层级顺序渲染
        for layer in sorted(self.layers.keys()):
            for entity in self.layers[layer]:
                renderable = entity.get_component(Renderable)
                transform = entity.get_component(Transform)
                
                if renderable.sprite:
                    # 计算缩放后的尺寸
                    if transform.scale != 1.0:
                        width = int(renderable.sprite.get_width() * transform.scale)
                        height = int(renderable.sprite.get_height() * transform.scale)
                        scaled_sprite = pygame.transform.scale(renderable.sprite, (width, height))
                        self.screen.blit(scaled_sprite, (transform.x, transform.y))
                    else:
                        self.screen.blit(renderable.sprite, (transform.x, transform.y))
        
        # DEBUG: 显示当前事件队列
        if self.world.events:
            print(f"[RenderSystem] 当前事件队列: {len(self.world.events)} 个事件")

class PhysicsSystem(System):
    """物理系统"""
    def update(self, entities: List[Entity], delta_time: float):
        for entity in entities:
            if not entity.has_component(Physics) or not entity.has_component(Transform):
                continue
                
            physics = entity.get_component(Physics)
            transform = entity.get_component(Transform)
            
            # 更新位置
            transform.x += physics.velocity_x * delta_time
            transform.y += physics.velocity_y * delta_time
            
            # 更新碰撞体位置
            if physics.collider:
                physics.collider.x = transform.x
                physics.collider.y = transform.y
                
            # 碰撞检测并触发事件
            if physics.collider:
                for other in entities:
                    if other.id == entity.id or not other.has_component(Physics):
                        continue
                    other_physics = other.get_component(Physics)
                    if other_physics.collider and physics.collider.colliderect(other_physics.collider):
                        # 触发碰撞事件
                        event_data = {
                            "type": "collision",
                            "entity1_id": entity.id,
                            "entity2_id": other.id
                        }
                        self.world.events.append(event_data)
                        print(f"[PhysicsSystem] 触发碰撞事件: {event_data}")
                        
                        # 碰撞后处理：伤害计算
                        if entity.has_component(Weapon) and other.has_component(Health):
                            # 武器实体碰撞生物实体
                            weapon = entity.get_component(Weapon)
                            health = other.get_component(Health)
                            health.current -= weapon.damage
                            print(f"[PhysicsSystem] 实体 {other.id} 受到 {weapon.damage} 点伤害")
                            
                            # 不再触发分数更新事件（伤害不加分）

class PlayerControlSystem(System):
    """玩家控制系统(支持双人)"""
    def update(self, entities: List[Entity], delta_time: float):
        keys = pygame.key.get_pressed()
        
        for entity in entities:
            if not entity.has_component(PlayerControl) or not entity.has_component(Physics):
                continue
                
            control = entity.get_component(PlayerControl)
            physics = entity.get_component(Physics)
            
            # 处理移动输入
            physics.velocity_x = 0
            physics.velocity_y = 0
            
            if keys[control.up_key]:
                physics.velocity_y = -control.speed
            if keys[control.down_key]:
                physics.velocity_y = control.speed
            if keys[control.left_key]:
                physics.velocity_x = -control.speed
            if keys[control.right_key]:
                physics.velocity_x = control.speed

class WeaponSystem(System):
    """武器系统"""
    def __init__(self):
        self.projectile_group = pygame.sprite.Group()
    
    def update(self, entities: List[Entity], delta_time: float):
        current_time = pygame.time.get_ticks() / 1000.0
        
        # 处理武器投掷事件（遍历事件副本）
        print(f"[WeaponSystem] 待处理事件数: {len(self.world.events)}")
        for event in self.world.events[:]:
            if event["type"] == "throw_weapon":
                print(f"[WeaponSystem] 处理事件: {event}")
                owner_id = event["owner_id"]
                target_id = event.get("target_id", None)  # 目标实体ID
                
                # 查找拥有者实体
                owner_entity = next((e for e in entities if e.id == owner_id), None)
                if owner_entity is None:
                    print(f"[WeaponSystem] 错误: 找不到拥有者实体 {owner_id}")
                    self.world.events.remove(event)
                    continue
                if not owner_entity.has_component(Transform):
                    print(f"[WeaponSystem] 错误: 拥有者实体 {owner_id} 缺少Transform组件")
                    self.world.events.remove(event)
                    continue
                
                # 创建投掷物实体
                projectile = Entity()
                transform = owner_entity.get_component(Transform)
                projectile.add_component(Transform(
                    x=transform.x,
                    y=transform.y
                ))
                # 创建一个简单的矩形作为精灵
                sprite = pygame.Surface((10, 10))
                sprite.fill((255, 0, 0))  # 红色方块
                projectile.add_component(Renderable(sprite=sprite, visible=True))
                # 设置物理属性：向右投掷（假设owner_id为1是玩家1，向右；玩家2则向左）
                velocity_x = 5 if owner_id == 1 else -5
                projectile.add_component(Physics(
                    velocity_x=velocity_x,
                    velocity_y=0,
                    collider=pygame.Rect(0, 0, 10, 10)
                ))
                projectile.add_component(Weapon(
                    damage=10,
                    owner_id=owner_id
                ))
                # 添加关系组件指向目标（如果有）
                if target_id is not None:
                    projectile.add_component(Relation(relations={"target": target_id}))
                    print(f"[WeaponSystem] 创建投掷物指向目标 {target_id}")
                else:
                    print(f"[WeaponSystem] 创建无目标投掷物")
                
                self.world.entities.append(projectile)
                self.world.events.remove(event)
                print(f"[WeaponSystem] 事件处理完成")
        for entity in entities:
            if not entity.has_component(Weapon):
                continue
                
            weapon = entity.get_component(Weapon)
            
            # 冷却时间处理
            if current_time - weapon.last_attack_time < weapon.cooldown:
                continue
            
            # 检测开火输入
            if entity.has_component(PlayerControl):
                control = entity.get_component(PlayerControl)
                keys = pygame.key.get_pressed()
                if keys[control.fire_key]:
                    print(f"Firing weapon for player {control.player_id}")
                    weapon.last_attack_time = current_time
                    # 创建子弹实体
                    bullet = Entity()
                    bullet.add_component(Transform(
                        x=entity.get_component(Transform).x,
                        y=entity.get_component(Transform).y
                    ))
                    bullet.add_component(Physics(
                        velocity_x=0,
                        velocity_y=-weapon.projectile_speed if control.player_id == 1 else weapon.projectile_speed,
                        collider=pygame.Rect(0, 0, 8, 8)
                    ))
                    bullet.add_component(Weapon(
                        damage=weapon.damage,
                        owner_id=entity.id
                    ))
                    self.world.entities.append(bullet)

class AISystem(System):
    """AI系统"""
    def update(self, entities: List[Entity], delta_time: float):
        for entity in entities:
            if not entity.has_component(AI) or not entity.has_component(Physics):
                continue
                
            ai = entity.get_component(AI)
            physics = entity.get_component(Physics)
            
            # 简单AI行为
            if ai.behavior_type == "wander":
                # 随机徘徊逻辑
                if random.random() < 0.02:  # 2%概率改变方向
                    physics.velocity_x = random.uniform(-ai.wander_speed, ai.wander_speed)
                    physics.velocity_y = random.uniform(-ai.wander_speed, ai.wander_speed)

class StateSystem(System):
    """游戏状态系统"""
    def __init__(self):
        self.player1_score = 0
        self.player2_score = 0
        self.game_state = {
            "game_over": False,
            "winner": ""
        }
    
    def update(self, entities: List[Entity], delta_time: float):
        # 处理游戏事件
        for event in self.world.events:
            if event["type"] == "score_update":
                print(f"[StateSystem] 处理分数更新: {event}")
                if event["player_id"] == 1:
                    self.player1_score += event["amount"]
                    print(f"[StateSystem] 玩家1新分数: {self.player1_score}")
                else:
                    self.player2_score += event["amount"]
                    print(f"[StateSystem] 玩家2新分数: {self.player2_score}")
            
            # 处理死亡事件（玩家死亡给对手加分）
            elif event["type"] == "death":
                player_id = event["player_id"]
                opponent_id = 2 if player_id == 1 else 1
                print(f"[StateSystem] 玩家{player_id}死亡，玩家{opponent_id}加1分")
                
                # 给对手加分
                self.world.events.append({
                    "type": "score_update",
                    "player_id": opponent_id,
                    "amount": 1
                })
        
        # 检查游戏结束条件
        if not self.game_state["game_over"]:
            if self.player1_score >= 10:
                self.game_state["game_over"] = True
                self.game_state["winner"] = "Zha"
                print(f"Game over! Winner: Zha")
            elif self.player2_score >= 10:
                self.game_state["game_over"] = True
                self.game_state["winner"] = "Bing"
                print(f"[StateSystem] 游戏结束! 胜利者: Bing")

class HealthSystem(System):
   """健康系统（处理血量变化和死亡事件）"""
   def update(self, entities: List[Entity], delta_time: float):
       for entity in entities:
           if not entity.has_component(Health):
               continue
               
           health = entity.get_component(Health)
           
           # 无敌状态处理
           if health.invincible:
               health.invincible_timer -= delta_time
               if health.invincible_timer <= 0:
                   health.invincible = False
                   print(f"[HealthSystem] 实体 {entity.id} 无敌状态结束")
           
           # 死亡检测
           if health.current <= 0:
               print(f"[HealthSystem] 实体 {entity.id} 死亡")
               
               # 触发死亡事件（需要PlayerControl组件来识别玩家）
               if entity.has_component(PlayerControl):
                   player_id = entity.get_component(PlayerControl).player_id
                   self.world.events.append({
                       "type": "death",
                       "player_id": player_id
                   })
                   print(f"[HealthSystem] 触发玩家{player_id}死亡事件")
               else:
                   print(f"[HealthSystem] 实体 {entity.id} 死亡但不是玩家")